import React, {useEffect, useState} from 'react'
import {Button, Space, TreeSelect, message, Cascader} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import {getSupplierArchivesList} from '@/service/supplier/supplierArchives'
import {getDict} from '@/service/common/dict'
import {getSupplierType, translateDataToTree} from '@/utils/common'
import {getCompany} from '@/service/common'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'

interface DataType {
	showArchivesAuditButton: any
	showEditButton: any
	archivesInstanceId: string
	id: string | string[] | null
	supplierCode: string
	supplierName: string
	orgId: string
	serviceType: string
	number: string
	contacts: string
	status: number
	date: string
}

const formItemLayout = {
	labelCol: {flex: '90px'},
	wrapperCol: {flex: '1'},
}

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const admittance = (props: {
	user: {orgId: string | number; userId: string | number}
}) => {
	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [supplierTypeData, setSupplierTypeData] =
		useState<supplierAPI.supplierType>([])
	const [companyData, setCompanyData] = useState([])
	const [loading, setLoading] = useState<boolean>(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	// 获取公司列表
	const onCompany = () => {
		getCompany({merchantId: props.user.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props.user.orgId])
	// 获取供应商档案列表
	const getData = () => {
		setLoading(true)
		getSupplierArchivesList({...params, auditResult: 4, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	/** 拾取任务 */
	// const pickTask = (processInstanceId: string) => {
	// 	claimTaskCandidate({
	// 		reviewerId: props?.user?.userId,
	// 		processInstanceId,
	// 	})
	// }
	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'ZC_GYS',
					'JC_GYS',
					'CZ_GYS',
					'SP_GYS',
					'DYY_GYS',
					'CS_GYS',
					'Project_Status',
					'Project_Bid_Section',
					'Enterprise_Nature',
				],
			},
			(res: any) => {
				const newData = getSupplierType([
					res.ZC_GYS,
					res.JC_GYS,
					res.CZ_GYS,
					res.SP_GYS,
					res.DYY_GYS,
					res.CS_GYS,
				])
				setSupplierTypeData(newData)
			},
		)
	}, [])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: any) => {
		const datas: any = {
			id: record?.id,
			status: record?.status,
			contactPhone: record?.contactPhone,
		}
		if (type === 'examine') {
			datas.examine = 'true'
			datas.processInstanceId = record?.archivesInstanceId
		}
		history.push({
			pathname: `/supplier/archives/${type}`,
			query: datas,
		})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '供应商编号',
			dataIndex: 'supplierCode',
			align: 'center',
			width: 120,
		},
		{
			title: '供应商名称',
			dataIndex: 'supplierName',
			align: 'center',
			width: 160,
		},
		{
			title: '供应商所属公司',
			dataIndex: 'orgId',
			align: 'center',
			width: 160,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text?.split(',') || []}
							disabled
							multiple
							maxTagCount={3}
							maxTagPlaceholder="..."
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							treeDefaultExpandAll
							fieldNames={fieldNames}
							treeDataSimpleMode
							treeData={companyData}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '供应商类型',
			dataIndex: 'supplierType',
			align: 'center',
			width: 120,
			render: (text) => (
				<Cascader
					disabled
					value={text?.split(',')}
					options={supplierTypeData}
				/>
			),
		},
		{
			title: '合同数量',
			dataIndex: 'contractNum',
			align: 'center',
			width: 120,
		},
		{
			title: '供应商联系人/电话',
			dataIndex: 'contactPhone',
			align: 'center',
			width: 180,
		},
		{
			title: '供应商状态',
			dataIndex: 'status',
			align: 'center',
			width: 120,
			render: (text) => <>{text === 1 ? '启用' : '禁用'}</>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_supplier_archives_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('details', record)
							}}>
							详情
						</Button>
					</Permissions>
					{record?.showEditButton ? (
						<div>
							{record.status === 1 ? (
								<Permissions permissionID="amc_supplier_archives_edit">
									<Button
										type="link"
										onClick={() => {
											onDetails('disable', record)
										}}>
										禁用
									</Button>
								</Permissions>
							) : (
								<Permissions permissionID="amc_supplier_archives_edit">
									<Button
										type="link"
										onClick={() => {
											onDetails('enable', record)
										}}>
										启用
									</Button>
								</Permissions>
							)}
						</div>
					) : (
						''
					)}
					{record?.showArchivesAuditButton ? (
						<Permissions permissionID="amc_supplier_archives_examine">
							<Button
								type="link"
								onClick={() => {
									// pickTask(record?.archivesInstanceId)
									onDetails('examine', record)
								}}>
								审核
							</Button>
						</Permissions>
					) : (
						''
					)}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '供应商编号',
					name: 'supplierCode',
					key: 'supplierCode',
				},
				{
					type: 'input',
					label: '供应商名称',
					name: 'supplierName',
					key: 'supplierName',
				},
				{
					type: 'cascader',
					label: '供应商类型',
					name: 'supplierType',
					key: 'supplierType',
					items: supplierTypeData,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					key: 'status',
					name: 'status',
					label: '供应商状态',
					keys: 'value',
					title: 'text',
					items: [
						{
							value: 1,
							text: '启用',
						},
						{
							value: 2,
							text: '禁用',
						},
					],
				},
				{},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		const seachData = {
			...values,
			supplierType: values?.supplierType?.toString(),
		}
		setSearchData(seachData)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	return (
		<div className={styles.admittance}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(admittance)
